#include "Triangle.h"
#include "Graph.h"

#include <vector>
#include <utility>
#include <algorithm>

#include <iostream>

using namespace std;

bool trianglePointSortPredicate(
        const pair<float,float>& d1,
        const pair<float,float>& d2)
{
      return d1.second < d2.second;
}

Triangle::Triangle(
        float x1, float y1,
        float x2, float y2,
        float x3, float y3){
    points.push_back(pair<float, float>(x1, y1));
    points.push_back(pair<float, float>(x2, y2));
    points.push_back(pair<float, float>(x3, y3));

    pair<float, float> p (x3, y3);
    pair<float, float> p2 (p2);

    // DEBUG
    // cout << getCenter().second << endl;
}

Triangle::~Triangle(){
}

pair<float,float> Triangle::operator[](int i) const {
    return points[i];
}

bool Triangle::isAdjacent(Triangle *t){
    int i, j;
    int count = 0;

    for(i=0; i<3; i++){
        for(j=0; j<3; j++){
            if( (*this)[i] == (*t)[j] ) count++;
        }
    }

    if(count>1) return true;
    return false;
}

bool Triangle::containPoint(float *p){
    bool resp = false;

    // cout << "(" << points[0].second << ", " << points[1].second << ", " << points[2].second << ")" << endl;
    // std::sort(points.begin(), points.end(), trianglePointSortPredicate);

//  float m1 =
//      (points[1].second-points[0].second)/(points[1].first-points[0].first);
//  float m2 =
//      (points[2].second-points[1].second)/(points[2].first-points[1].first);
//  float m3 =
//      (points[2].second-points[0].second)/(points[2].first-points[0].first);

    // y = m(x - x0) + y0


    return resp;
}

pair<float, float> Triangle::getCenter(){
    int i;
    pair<float, float> point;
    float x=0.0f, y=0.0f;

    for(i=0; i<3; i++){
        point = (*this)[i];

        // DEBUG
        // cout << "Agregando (" << point.first << ", " << point.second << ")" << endl;

        x += point.first;
        y += point.second;
    }

    return pair<float, float>(x/3, y/3);
}

void buildGraphFromTriangles(){
    int i, j, n;
    Node *node;
    pair<float, float> point1;

    // Generamos todos los nodos
    for(i=0, n=triangles.size(); i<n; i++){
        point1 = triangles[i]->getCenter();
        node = new Node(point1.first, point1.second);

        graph.addNode(node);
        triangles[i]->node = node;

        // Adicionalmente, ordenamos los puntos por coordenadas Y
        std::sort(
                triangles[i]->points.begin(),
                triangles[i]->points.end(),
                trianglePointSortPredicate);
    }

    for(i=0, n=triangles.size(); i<n; i++){
        point1 = triangles[i]->getCenter();

        for(j=i+1; j<n; j++){
            if(triangles[i]->isAdjacent(triangles[j])){
                graph.addDoubleEdge(triangles[i]->node, triangles[j]->node);
            }
        }
    }
}

